package com.bw.finance.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bw.finance.auth.UserInfo;
import com.bw.finance.conf.ResponseResult;
import com.bw.finance.eneity.locana.EbankLoanInfo;
import com.bw.finance.eneity.user.EbankBorrower;
import com.bw.finance.eneity.user.EbankInvestor;
import com.bw.finance.eneity.user.res.Loginuser;
import com.bw.finance.mapper.EbankBorrowerMapper;
import com.bw.finance.service.IEbankBorrowerService;
import com.bw.finance.service.IEbankInvestorService;
import com.bw.finance.utils.MD5Utils;
import com.bw.finance.utils.Photo.DanbaoImgUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lizhengqian
 * @since 2020-08-17
 */
@Service
public class EbankBorrowerServiceImpl extends ServiceImpl<EbankBorrowerMapper, EbankBorrower> implements IEbankBorrowerService {

    private static final Logger log = LoggerFactory.getLogger(EbankBorrowerServiceImpl.class);

    @Autowired
    private IEbankBorrowerService ebankBorrowerService;

    @Autowired
    private IEbankInvestorService investorService;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public ResponseResult getBorrowerList(int pagenum, int pagesize, EbankBorrower ebankBorrower) {
        ResponseResult result = ResponseResult.SUCCESS();
        PageHelper.startPage(pagenum,pagesize);
        try {
            PageHelper.startPage(pagenum,pagesize);
            System.out.println("开始列表查询");
            QueryWrapper<EbankBorrower> queryWrapper = new QueryWrapper<>();
            if (ebankBorrower.getFullName()!=null){
                queryWrapper.like("FULL_NAME",ebankBorrower.getFullName());
            }
            List<EbankBorrower> list = ebankBorrowerService.list(queryWrapper);
            PageInfo pageInfo = new PageInfo(list);
            result.setMessage("查询成功");
            result.setResult(pageInfo);
        }catch (Exception e){
            e.printStackTrace();
            result.setMessage("查询异常!");
            result.setSuccess(false);
            return result;
        }
        return result;
    }

    @Override
    public ResponseResult toBlackName(Long id) {
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            log.info("开始拉入黑名单");
            EbankBorrower borrower = ebankBorrowerService.getById(id);
            borrower.setStatus(0);
            ebankBorrowerService.saveOrUpdate(borrower);
            log.info("结束拉入黑名单");
        }catch (Exception e){
            e.printStackTrace();
            result.setMessage("拉入异常!");
            result.setSuccess(false);
            return result;
        }
        return result;
    }

    @Override
    public ResponseResult login(Loginuser user, HttpServletResponse response) {
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            user.setPwd(MD5Utils.md5Encrypt32Lower(user.getPwd()));
            if(user.getType()==0){
                QueryWrapper<EbankBorrower> queryWrapper=new QueryWrapper();
                queryWrapper.lambda().eq(EbankBorrower::getLoginName,user.getLoginName())
                        .eq(EbankBorrower::getLoginPwd,user.getPwd());
                EbankBorrower borrower = ebankBorrowerService.getOne(queryWrapper);
                if(borrower!=null){
                    UserInfo userInfo = new UserInfo(borrower.getId(), borrower.getLoginName());
                    String token= UUID.randomUUID().toString();
                    Cookie cookie = new Cookie("token",token);
                    cookie.setMaxAge(1800);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                    redisTemplate.opsForValue().set(token,userInfo);
                    redisTemplate.expire(token,30, TimeUnit.MINUTES);
                    borrower.setLastLoginTime(new Date());
                    ebankBorrowerService.saveOrUpdate(borrower);
                    Map mapinfo=new HashMap();
                    mapinfo.put("cususer",borrower);
                    mapinfo.put("token",token);
                    mapinfo.put("type",0);
                    result.setResult(mapinfo);
                    result.setMessage("登录成功");
                }else{
                    result.setMessage("用户或密码错误");
                    result.setSuccess(false);
                }
            }
            if(user.getType()==1){
                QueryWrapper<EbankInvestor> queryWrapper=new QueryWrapper();
                queryWrapper.lambda().eq(EbankInvestor::getLoginName,user.getLoginName())
                        .eq(EbankInvestor::getLoginPwd,user.getPwd());
                EbankInvestor investor = investorService.getOne(queryWrapper);
                if(investor!=null){
                    UserInfo userInfo = new UserInfo(investor.getId(), investor.getLoginName());
                    String token= UUID.randomUUID().toString();
                    Cookie cookie = new Cookie("token",token);
                    cookie.setMaxAge(1800);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                    redisTemplate.opsForValue().set(token,userInfo);
                    redisTemplate.expire(token,30, TimeUnit.MINUTES);
                    investor.setLastLoginTime(new Date());
                    investorService.saveOrUpdate(investor);
                    Map mapinfo=new HashMap();
                    mapinfo.put("cususer",investor);
                    mapinfo.put("token",token);
                    mapinfo.put("type",1);
                    result.setResult(mapinfo);
                    result.setMessage("登录成功");
                }else{
                    result.setMessage("用户或密码错误");
                    result.setSuccess(false);
                }
            }
        }catch (Exception e){
            result.setMessage("登录异常!");
            result.setSuccess(false);
            return result;
        }
        return result;
    }

    @Override
    public ResponseResult emailcheck(EbankBorrower borrower) {
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            String code = stringRedisTemplate.boundValueOps("YE:" +borrower.getTel()).get();
            if(code==null){
                result.setSuccess(false);
                result.setMessage("验证码已过期");
                log.info("验证码已过期");
                return result;
            }
            if(!code.equals(borrower.getCode())){
                result.setSuccess(false);
                result.setMessage("验证码输入错误");
                log.info("验证码输入错误");
                return result;
            }
            EbankBorrower ebankBorrower = ebankBorrowerService.getById(borrower.getId());
            ebankBorrower.setEmail(borrower.getEmail());
            ebankBorrowerService.saveOrUpdate(ebankBorrower);
            result.setMessage("保存成功");
        }catch (Exception e){
            log.error("邮箱保存失败"+e.toString());
            result.setSuccess(false);
            result.setMessage("邮箱保存异常"+e.toString());
        }
        return result;
    }

    @Override
    public EbankBorrower getborrowone(EbankLoanInfo ebankLoanInfo) {
        return ebankBorrowerService.getById(ebankLoanInfo.getBorrowerId());
    }

    @Override
    public ResponseResult finduser(Long id, Integer type) {
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            if(type==0){
                EbankBorrower borrower = ebankBorrowerService.getById(id);
                result.setResult(borrower);
            }
            if(type==1){
                EbankInvestor investor = investorService.getById(id);
                result.setResult(investor);
            }
        }catch (Exception e){
            log.error("信息查询失败"+e.toString());
            result.setSuccess(false);
            result.setMessage("信息查询异常"+e.toString());
        }
        return result;
    }
}
